const fs = require('fs');
const path = require('path');

/**
 * Module加载器
 * @param {string} dir 加载路径
 * @param {boolean} recursion 是否递归
 * @param {string} ext 扩展名
 * @returns 
 */
function module_loader(dir, recursion, ext = '.cjs') {
  const objs = {};
  const dirents = fs.readdirSync(dir, { withFileTypes: true });
  dirents.forEach(dirent => {
    const full_path = path.join(dir, dirent.name);
    if (dirent.isFile()) {
      if (dirent.name.toLowerCase().endsWith(ext)) {
        objs[dirent.name.slice(0, 0 - ext.length)] = require(full_path);
      }
    } else if (recursion) {
      let sub = module_loader(full_path, recursion, ext);
      Object.keys(sub).forEach(key => {
        objs[dirent.name + '.' + key] = sub[key];
      });
    }
  });
  return objs;
}

module.exports = class {
  constructor(props) {
    this.base = props.base || '';
  }

  load(dir, recursion, ext) {
    return module_loader(dir, recursion, ext);
  }

  loadConfig() {
    try {
      const name = (process.env.NODE_ENV || 'local') + '.cjs';
      return require(path.join(require.main.path, this.base, 'config', name));
    } catch (e) {
      console.error(e);
    }
  }

  loadController() {
    return module_loader(path.join(require.main.path, this.base, 'controller'), true);
  }

  loadService() {
    return module_loader(path.join(require.main.path, this.base, 'service'), true);
  }

  loadViewPage() {
    return module_loader(path.join(require.main.path, this.base, 'view'), true);
  }
}
